package fun.xinnix.handler;

import entity.SysUser;
import fun.xinnix.service.SysUserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;

import javax.annotation.Resource;
import java.util.HashSet;
import java.util.Set;

@Slf4j
public class UserRealm extends AuthorizingRealm {
    @Resource
    SysUserService sysUserService;

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        log.info("执行======》doGetAuthorizationInfo方法");
        String username = (String) principalCollection.getPrimaryPrincipal();
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        SysUser sysUser = sysUserService.findByUserName(username);
        Long roleId = sysUser.getRoleId();
        Set<String> roleList = new HashSet<>();
        roleList.add(String.valueOf(roleId));
        info.setRoles(roleList);
        return info;
    }


    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        log.info("执行======》doGetAuthenticationInfo");
        UsernamePasswordToken usernamePasswordToken = (UsernamePasswordToken) authenticationToken;
        SysUser sysUser = sysUserService.findByUserName(usernamePasswordToken.getUsername());
        if (sysUser == null) {
            return null;
        }
        return new SimpleAuthenticationInfo("", sysUser.getPassword(), "reaml-auth");
    }
}
